package com.module.mail
{
	import com.Connect;
	import com.connect.agreement.mclgc.Packet;
	import com.core.utils.StringUtil;
	import com.game.Global;
	import com.game.Group;
	import com.game.views.UIMediator;
	
	import events.PageEvent;
	
	import flash.events.MouseEvent;
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectProxy;
	
	import org.phprpc.util.PHPSerializer;
	import org.puremvc.as3.patterns.facade.Facade;
	
	import pops.MailDetail;
	import pops.MailPanel;

	public class MailManager
	{
		public static const SendMail:int = 1;
		public static const GetMails:int = 2;
		public static const GetContent:int = 3;
		public static const DeleteMails:int = 4;
		
		private static var lock:Boolean = true;
		
		public static var instance:MailManager = new MailManager();
		
		
		public function MailManager()
		{
			if(!lock)
				throw new Error("single");
			lock = false;
		}
		
		private var _panel:MailPanel;
		
		private var _detail:MailDetail;
		
		public var mails:ArrayCollection = new ArrayCollection();
		
		/**
		 * 每页大小
		 */
		public var pagesize:int = 8;
		/**
		 * 当前页
		 */
		private var _curpage:int = 1;
		
		/**
		 * 当前查看的邮件
		 */
		private var _curmailtitle:MailTitle;
		/**
		 * 当前查看的内容
		 */
		private var _curmailContent:MailContent;
		
		/**
		 * 停留在哪一个界面 1未读邮件 2收件箱
		 */
		private var type:int;
		
		/**
		 * 选中的列表
		 */
		private var checklist:Array = [];
		
		public function get curpage():int
		{
			return _curpage;
		}

		public function set curpage(value:int):void
		{
			_curpage = value;
			this.flushList();
		}

		public function get panel():MailPanel
		{
			return this._panel;
		}
		
		public function setPanel(panel:MailPanel):void
		{
			this._panel = panel;
			getMailList();
		}
		
		public function set detail(value:MailDetail):void
		{
			this._detail = value;
			this._detail.sendBtn.addEventListener(MouseEvent.CLICK,sendClickHandler);
		}
		
		public function get detail():MailDetail
		{
			return this._detail;
		}
		
		private function sendClickHandler(event:MouseEvent):void
		{
			sendMail(StringUtil.trim(this._detail.titleInput.text),StringUtil.trim(this._detail.contentInput.text),Global.ctrlrole.id,StringUtil.trim(this._detail.whoInput.text));
		}
		
		public function showMail(type:int):void
		{
			this.type = type;
			if(type == 1){
				this.panel.newmailtab.selected = true;
				this.panel.allmailtab.selected = false;
			} else {
				this.panel.newmailtab.selected = false;
				this.panel.allmailtab.selected = true;
			}
			flushList();
		}
		
		private var count:int = 0;
		
		private function flushList():void
		{
			checklist.length = 0;
			count = 0;
			this.mails.filterFunction = showPageFunc;
			this.mails.refresh();
			this.panel.deleteBtn.enabled = false;
		}
		
		private function showPageFunc(item:MailTitle):Boolean
		{
			if(this.type == 1){//当前页面是未读页面
				if(item.state == 1){
					count++;
					if(count>(this.curpage-1)*this.pagesize && count<=this.curpage*this.pagesize)
						return true;
					else
						return false;
				} else {
					return false;
				}
			} else {
				count++;
				if(count>(this.curpage-1)*this.pagesize && count<=this.curpage*this.pagesize)
					return true;
				else
					return false;
			}
		}
		
		public function toSend():void
		{
			if(this.detail.isPopUp){
				Facade.getInstance().sendNotification('close mail detail');
			}
			initMailDetail(2);
		}
		
		//上一页
		public function prePage(event:PageEvent):void
		{
			if(event.page>0 && event.page<=Math.ceil(this.mails.source.length/this.pagesize)){
				this.curpage = event.page;
				if(this.count > (this.curpage-1)*this.pagesize){
					this.panel.pagination.curpage = event.page;					
				} else {
					this.curpage--;
				}
			}
		}
		//下一页
		public function nextPage(event:PageEvent):void
		{
			if(event.page>0 && event.page<=Math.ceil(this.mails.source.length/this.pagesize)){
				this.curpage = event.page;
				if(this.count > (this.curpage-1)*this.pagesize){
					this.panel.pagination.curpage = event.page;					
				} else {
					this.curpage--;
				}
			}
		}
		//调转到页面
		public function toPage(event:PageEvent):void
		{
			if(event.page>0 && event.page<=Math.ceil(this.mails.source.length/this.pagesize)){
				this.curpage = event.page;
				if(this.count > (this.curpage-1)*this.pagesize){
					this.panel.pagination.curpage = event.page;					
				} else {
					this.curpage--;
				}
			}
		}
		//查看邮件
		public function showMailContent(mailtitle:Object):void
		{
			if(mailtitle is MailTitle){
				this._curmailtitle = mailtitle as MailTitle;
				this.getMailContent();
			}
		}
		private var dodeletelist:Array = null;
		//删除邮件
		public function deleteAll():void
		{
			var ids:String = '';
			for each(var mail:MailTitle in this.checklist)
			{
				ids += mail.id;
				if(this.checklist.indexOf(mail) < this.checklist.length-1)
					ids += ",";
			}
			dodeletelist = this.checklist.slice();
			var p:Packet = new Packet(true,Group.Mail,DeleteMails,PHPSerializer.serialize(ids));
			Connect.server.sendPackage(p);
		}
		
		//关闭查看的邮件或者是写邮件的界面
		public function closeDetail():void
		{
			PopUpManager.removePopUp(this._detail);
		}
		
		//初始化邮件面板
		public function initMailPanel():void
		{
			this.showMail(1);
			this.flushList();
		}
		/**
		 * 
		 * @param type 1=初始化查看 2=初始化发送
		 * 
		 */		
		public function initMailDetail(type:int=1):void
		{
			if(type == 1){
				this.detail.title = '查看信件';
				this.detail.titleInput.text = this._curmailtitle.title;
				this.detail.contentInput.text = this._curmailContent.content;
				this.detail.whoInput.text = this._curmailtitle.fromname;
				this.detail.sendBtn.visible = false;
				this.detail.tag.text = '';
				this.detail.titleInput.editable = false;
				this.detail.contentInput.editable = false;
				this.detail.whoInput.editable = false;
				this.detail.whoLabel.text = '发件人：';
			} else if(type == 2) {
				this.detail.title = '写信件';
				this.detail.titleInput.text = '';
				this.detail.contentInput.text = '';
				this.detail.whoInput.text = '';
				this.detail.sendBtn.visible = true;
				this.detail.tag.text = '';
				this.detail.titleInput.editable = true;
				this.detail.contentInput.editable = true;
				this.detail.whoInput.editable = true;
				this.detail.whoLabel.text = '收件人：';
			}
		}
		
		//点击选中某一封邮件
		public function checkMail(event:MouseEvent,data:Object):void
		{
			if(event.currentTarget.selected)
				this.checklist.push(data);
			else {
				var index:int = this.checklist.indexOf(data);
				if(index>-1){
					this.checklist.splice(index,1);
				}
			}
			if(this.checklist.length>0){
				this.panel.deleteBtn.enabled = true;
			} else {
				this.panel.deleteBtn.enabled = false;
			}
		}
		
		/**
		 * 发送邮件的私有函数，外部禁止访问 
		 * @param title
		 * @param content
		 * @param fromrid
		 * @param torid
		 * 
		 */
		private function sendMail(title:String,content:String,fromrid:int,towho:String):void
		{
			var sminfo:SendMailInfo = new SendMailInfo();
			sminfo.title = title;
			sminfo.content = content;
			sminfo.fromrid = fromrid;
			sminfo.towho = towho;
			var p:Packet = new Packet(true,Group.Mail,SendMail,PHPSerializer.serialize(sminfo));
			Connect.server.sendPackage(p);
		}
		
		/**
		 * 获得所有邮件的消息，外部禁止访问 
		 * 
		 */
		private function getMailList():void
		{
			var p:Packet = new Packet(true,Group.Mail,GetMails,PHPSerializer.serialize(Global.ctrlrole.id));
			Connect.server.sendPackage(p);	
		}
		
		/**
		 * 向服务端发送查看邮件内容的请求，外部禁止访问
		 * 
		 */
		private function getMailContent():void
		{
			var arr:Array;
			if(this._curmailtitle.state == 1)//未读邮件 发送邮件title的id
				arr = [this._curmailtitle.cid,this._curmailtitle.id];
			else//已读的邮件 不需要邮件title的id
				arr = [this._curmailtitle.cid];
			var p:Packet = new Packet(true,Group.Mail,GetContent,PHPSerializer.serialize(arr));
			Connect.server.sendPackage(p);
		}
		
		public function update(packet:Packet):void
		{
			if(!packet)
				return;
			switch(packet.cmd){
				case GetMails:
					this.mails.filterFunction = null;
					this.mails.removeAll();
					var list:Array = PHPSerializer.unserialize(packet.data);
					for each(var item:MailTitle in list){
						this.mails.addItem(item);
					}
					break;
				case GetContent:
					this._curmailtitle.state = 2;
					this.flushList();
					this._curmailContent = PHPSerializer.unserialize(packet.data);
					initMailDetail(1);
					Facade.getInstance().sendNotification(UIMediator.ShowMailContent);
					break;
				case SendMail:
					var ret:Object = PHPSerializer.unserialize(packet.data);
					if(ret is Boolean){
						if(ret){//发送邮件成功
							Facade.getInstance().sendNotification(UIMediator.CloseMailDetail);
						}
					} else {//接收到新邮件
						this.mails.addItem(ret);
					}
					break;
				case DeleteMails:
					if(dodeletelist && this.dodeletelist.length>0){
						this.mails.filterFunction = null;
						this.mails.refresh();
						for each(var mail :MailTitle in dodeletelist){
							this.mails.removeItemAt(this.mails.getItemIndex(mail));
						}
						flushList();
					}
					break;
			}
		}
	}
}